home *** CD-ROM | disk | FTP | other *** search
/ Celestin Apprentice 5 / Apprentice-Release5.iso / Source Code / By the Book / Learn C++ (CodeWarrior) / Chap 07.07 - equals / equals.cp < prev    next >
Text File  |  1995-10-31  |  2KB  |  80 lines

  1. #include <iostream.h>
  2. #include <string.h>
  3.  
  4.  
  5. //---------------------------------------  String
  6.  
  7. class String
  8. {
  9.     private:
  10.         char        *s;
  11.         short        stringLength;
  12.         
  13.     public:
  14.                         String( char *theString );
  15.                         ~String();
  16.         void        DisplayAddress();
  17.         String    &operator=( const String &fromString );
  18. };
  19.  
  20. String::String( char *theString )
  21. {
  22.     stringLength = strlen( theString );
  23.     s = new char[ stringLength + 1 ];
  24.     
  25.     strcpy( s, theString );
  26. }
  27.  
  28. String::~String()
  29. {
  30.     delete [] s;
  31. }
  32.  
  33. void    String::DisplayAddress()
  34. {
  35. //    I added an extra line to the DisplayAddress function
  36. //    because both sets of address in the program were
  37. //    turning out to be the same. I now print out the string
  38. //    along with the string address. Now when you run the program,
  39. //    you can see that the first time you print captain and doctor,
  40. //    they contain different strings, but the second time, they
  41. //    contain the same string, even though their addresses
  42. //    didn't change.
  43. //        Sorry for any confusion -- Dave Mark 10/31//95
  44.     cout << "String address: " << (unsigned long)s << "\n";
  45.     cout << "       content: " << s << "\n\n";
  46. }
  47.  
  48. String    &String::operator=( const String &fromString )
  49. {
  50.     delete [] s;
  51.     
  52.     stringLength = fromString.stringLength;
  53.     
  54.     s = new char[ stringLength + 1 ];
  55.     
  56.     strcpy( s, fromString.s );
  57.     
  58.     return( *this );
  59. }
  60.  
  61.  
  62. //---------------------------------------  main()
  63.  
  64. int    main()
  65. {
  66.     String        captain( "Picard" );
  67.     String        doctor( "Crusher" );
  68.     
  69.     captain.DisplayAddress();
  70.     doctor.DisplayAddress();
  71.     
  72.     cout << "-----\n";
  73.     
  74.     doctor = captain;
  75.     
  76.     captain.DisplayAddress();
  77.     doctor.DisplayAddress();
  78.     
  79.     return 0;
  80. }